package com.qinggeng.project.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.com.google.common.collect.Lists;
import com.qinggeng.common.enums.GoodsOrderEnum;
import com.qinggeng.common.enums.TopGoodsEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.common.utils.text.Convert;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.project.api.dto.GoodsCollectDto;
import com.qinggeng.project.api.dto.GoodsDto;
import com.qinggeng.project.api.dto.GoodsInfoDto;
import com.qinggeng.project.api.dto.ShareDto;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.domain.vo.GoodsKeyWordsVO;
import com.qinggeng.project.system.dto.GoodsKeyWordDTO;
import com.qinggeng.project.system.mapper.GoodsMapper;
import com.qinggeng.project.system.mapper.GoodsMarkMapper;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 商品信息Service业务层处理
 *
 * @author qinggeng
 * @date 2020-06-15
 */
@Service
@Slf4j
public class GoodsServiceImpl implements IGoodsService
{

    private static final BigDecimal ZERO=new BigDecimal(0);

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsMarkMapper goodsMarkMapper;

    @Autowired
    private IUserCartService userCartService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private GoodsImgServiceImpl goodsImgService;

    @Autowired
    private DistributionConfigService distributionConfigService;

    @Autowired
    private  ISysConfigService sysConfigService;
    @Autowired
    private IGoodsPercentService goodsPercentService;
    @Autowired
    private IDistributionPointService pointService;
    @Autowired
    private ISysUserService sysUserService;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private IDistributionPointService distributionPointService;

    /**
     * 查询商品信息
     *
     * @param goodsId 商品信息ID
     * @return 商品信息
     */
    @Override
    public Goods selectGoodsById(Long goodsId)
    {
        return goodsMapper.selectGoodsById(goodsId);
    }

    /**
     * 查询商品信息
     *
     * @param goodsId 商品信息ID
     * @return 商品信息
     */
    @Override
    public Goods selectGoodsByIdYg(Long goodsId) {
        return goodsMapper.selectGoodsByIdYg(goodsId);
    }

    /**
     * 查询商品信息列表
     *
     * @param goods 商品信息
     * @return 商品信息
     */
    @Override
    public List<Goods> selectGoodsList(Goods goods)
    {
        return goodsMapper.selectGoodsListForOne(goods);
    }

    @Override
    public List<Goods> systemSelectGoodsList(Goods goods) {
        return goodsMapper.systemSelectGoodsListForOne(goods);
    }

    /**
     * 新增商品信息
     *
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    public int insertGoods(Goods goods)
    {
        goods.setCreateTime(DateUtils.getNowDate());
        return goodsMapper.insertGoods(goods);
    }

    /**
     * 修改商品信息
     *
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    public int updateGoods(Goods goods)
    {
        goods.setUpdateTime(DateUtils.getNowDate());
        return goodsMapper.updateGoods(goods);
    }

    /**
     * 批量删除商品信息
     *
     * @param goodsIds 需要删除的商品信息ID
     * @return 结果
     */
    @Override
    public int deleteGoodsByIds(Long[] goodsIds)
    {
        return goodsMapper.deleteGoodsByIds(goodsIds);
    }

    /**
     * 删除商品信息信息
     *
     * @param goodsId 商品信息ID
     * @return 结果
     */
    @Override
    public int deleteGoodsById(Long goodsId)
    {
        return goodsMapper.deleteGoodsById(goodsId);
    }


    @Override
    public List<GoodsDto> selectGoodsListDto(Goods goods) {
        String distTime = distributionConfigService.getDistDateTime();

        List<GoodsDto> goodsDtoList=goodsMapper.selectGoodsListDto(goods);
        //根据商品标识查出所有的商品标签
        List<SysDictData> goods_marks = sysDictDataService.selectDictDataByType("goods_mark");
        for (GoodsDto goodsDto:goodsDtoList) {
            goodsDto.setGoodsMarkList(getGoodsMarkList(goodsDto,goods_marks));
            goodsDto.setDistTime(distTime);
        }
        return goodsDtoList;
    }

    @Override
    public List<GoodsDto> selectGoodsListDto1(Goods goods) {
        List<GoodsDto> goodsDtoList=goodsMapper.selectGoodsListDto1(goods);
        //根据商品标识查出所有的商品标签
        List<SysDictData> goods_marks = sysDictDataService.selectDictDataByType("goods_mark");
        //售后信息
        String afterSaleInformation = (String) sysConfigService.selectConfigByKey("sys.saleAfter.information");
        List<String> goodsIds= new ArrayList<String>();
        //配送时间
        String distTime = distributionConfigService.getDistDateTime();

        for (GoodsDto goodsDto:goodsDtoList) {
            goodsDto.setGoodsMarkList(getGoodsMarkList(goodsDto,goods_marks));
            goodsIds.add(String.valueOf(goodsDto.getGoodsId()));
            //预计送达时间
            goodsDto.setDistTime(distTime);
            //售后信息
            goodsDto.setAfterSaleInformation(afterSaleInformation);
        }
        if (!goodsIds.isEmpty()){
            Map<String,List<String>> map=goodsImgService.listLongImages(goodsIds);
            for (GoodsDto goodsDto:goodsDtoList) {
                List<String> images=map.get(String.valueOf(goodsDto.getGoodsId()));
                log.info("goodsId {}   images {}",goodsDto.getGoodsId(),images);
                if (images!=null&&!images.isEmpty()){
                    int index= new Random().nextInt(images.size());
                    goodsDto.setGoodsImg(images.get(index));
                    goodsDto.setGoodsLongImg(images.get(index));
                }
            }
        }

        return goodsDtoList;
    }

    @Override
    public GoodsInfoDto selectGoodsDtoById(Long goodsId, Long shopId, Float lng, Float lat) {
        GoodsInfoDto dto= goodsMapper.selectGoodsDtoById(goodsId, shopId);
        if (null ==dto){
            throw  new CustomException("商品不存在");
        }
        String listImg=goodsImgService.getDetailsImages(goodsId);
        dto.setListImg(listImg);
        String longImages= goodsImgService.getLongImages(goodsId);
        dto.setGoodsLongImg(longImages);
        String mainImgs=goodsImgService.getMainImage(goodsId);
        dto.setGoodsImg(mainImgs);
        return dto;
    }

    @Override
    public GoodsInfoDto selectGoodsDtoById(Long goodsId, Long shopId) {
        try {
            log.info("goodsId {} shopId {}",goodsId,shopId);
            GoodsInfoDto dto = goodsMapper.selectGoodsDtoById(goodsId, shopId);
            String goodsType=dto.getGoodsType();
            String defaultType="40";
            if (null ==dto){
                throw  new CustomException("商品不存在");
            }
            if (defaultType.equals(goodsType)){
                return dto;
            }
            String listImg = goodsImgService.getDetailsImages(goodsId);
            String longImages = goodsImgService.getLongImages(goodsId);
            String mainImgs = goodsImgService.getMainImage(goodsId);
            dto.setListImg(listImg);
            dto.setGoodsLongImg(longImages);
            dto.setGoodsImg(mainImgs);
            return dto;
        }catch (Exception e) {
            log.error(e.getMessage());
            throw new CustomException("查询商品信息失败");
        }
    }

    /**
     * 查询包含子分类id的商品集合
     * @param goods
     * @return
     */
    @Override
    public List<GoodsDto> selectGoodsListDtoForOne(Goods goods) {
        List<GoodsDto> goodsDtoList=goodsMapper.selectGoodsListDtoforOne(goods);
        //根据商品标识查出所有的商品标签
        List<SysDictData> goods_marks = sysDictDataService.selectDictDataByType("goods_mark");
        //售后信息
        String afterSaleInformation = (String) sysConfigService.selectConfigByKey("sys.saleAfter.information");
        String distTime=distributionConfigService.getDistDateTime();
        List<String> goodsIds= new ArrayList<String>();
        for (GoodsDto goodsDto:goodsDtoList) {
            goodsIds.add(String.valueOf(goodsDto.getGoodsId()));
            goodsDto.setGoodsMarkList(getGoodsMarkList(goodsDto,goods_marks));
            //预计送达时间
            goodsDto.setDistTime(distTime);
            //售后信息
            goodsDto.setAfterSaleInformation(afterSaleInformation);
            //绑定自动更换图片
            String img=goodsImgService.getMainImage(goodsDto.getGoodsId());
            goodsDto.setGoodsImg(img);
        }
        if (!goodsIds.isEmpty()){
            Map<String,List<String>> map=goodsImgService.listLongImages(goodsIds);
            for (GoodsDto goodsDto:goodsDtoList) {
                List<String> images=map.get(String.valueOf(goodsDto.getGoodsId()));
                log.info("goodsId {}   images {}",goodsDto.getGoodsId(),images);
                if (images!=null&&!images.isEmpty()) {
                    int index = new Random().nextInt(images.size());
                    goodsDto.setGoodsLongImg(images.get(index));
                    goodsDto.setGoodsImg(images.get(index));
                }
            }
        }

        return goodsDtoList;
    }




    @Override
    public int logicalDeleteGoodsByIds(Long[] goodsIds) {
        return goodsMapper.logicalDeleteGoodsByIds(goodsIds);
    }

    public List<GoodsMark> getGoodsMarkList(GoodsDto goodsDto,List<SysDictData> goods_marks){
        String proportion = null;
        try {
            proportion = goodsDto.getLinePrice().subtract(goodsDto.getGroupPrice()).divide(goodsDto.getLinePrice(),2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<GoodsMark> goodsMarkList=new ArrayList<>();
        String mark = goodsDto.getGoodsMark();
        if(StringUtils.isNotEmpty(mark)){
            //拆分参数
            String[] markIds=mark.split(",");
            for (String id:markIds) {
                if (goods_marks !=null && goods_marks.size()>0){
                    for (SysDictData goods_mark : goods_marks) {
                        //如果id=dictValue则插入集合
                        if (id.equals(goods_mark.getDictValue())){
                            GoodsMark goodsMark = new GoodsMark();
                            goodsMark.setId(id);
                            goodsMark.setMark(id.equals("50")?
                                    goods_mark.getDictLabel()+(StringUtils.isEmpty(goodsDto.getProportion())?(proportion+"%"):goodsDto.getProportion()):goods_mark.getDictLabel());
                            goodsMarkList.add(goodsMark);
                        }
                    }
                }
//                GoodsMark goodsMark = goodsMarkMapper.selectGoodsMarkById(id);
//                if (goodsMark != null) {
//                    goodsMarkList.add(goodsMark);
//                }
            }
        }
        return goodsMarkList;
    }


    /**
     * 获取用户购物车信息，设置商品加入购物车的数量
     * @param goodsDtoList
     * @param shopId
     * @return
     */
    @Override
    public List<GoodsDto> setGoodsDtoFromUserCart(List<GoodsDto> goodsDtoList,Long shopId,Long userId){
        for (GoodsDto goodsDto : goodsDtoList) {
            UserCart userCart= userCartService.selectUserCartByUserId(goodsDto.getGoodsId(), shopId, userId);
            if (userCart != null){
                goodsDto.setCartNum(userCart.getGoodsNum());
                goodsDto.setCartId(userCart.getCartId());
            }else{
                goodsDto.setCartNum(0);
            }
        }
        return goodsDtoList;
    }

    /**
     * 查询最大主类Id
     * @return
     */
    @Override
    public Long selectMaxGoodsId() {
        return goodsMapper.selectMaxGoodsId();
    }

    /**
     * 商品sKu集合
     * @param goods
     * @return
     */
    @Override
    public List<GoodsDto> selectGoodsSkuList(Goods goods) {
        return goodsMapper.selectGoodsSkuList(goods);
    }

    @Override
    public GoodsMark selectGoodsMarkById(String id) {
        return goodsMapper.selectGoodsMarkById(id);
    }

    @Override
    public List<GoodsMark> getGoodsMarkList(GoodsCollectDto collectDto,String goodsMark) {
        String proportion = null;
        try {
            proportion = collectDto.getLinePrice().subtract(collectDto.getGroupPrice()).divide(collectDto.getLinePrice(),2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            proportion = "";
            e.printStackTrace();
        }
        //根据商品标识查出所有的商品标签
        List<SysDictData> goods_marks = sysDictDataService.selectDictDataByType("goods_mark");
        List<GoodsMark> goodsMarkList=new ArrayList<>();
        if(StringUtils.isNotEmpty(goodsMark)){
            //拆分参数
            String[] markIds=goodsMark.split(",");
            for (String id:markIds) {
                if (goods_marks !=null && goods_marks.size()>0){
                    for (SysDictData goods_mark : goods_marks) {
                        //如果id=dictValue则插入集合
                        if (id.equals(goods_mark.getDictValue())){
                            GoodsMark mark = new GoodsMark();
                            mark.setId(id);
                            mark.setMark(id.equals("50")?
                                    goods_mark.getDictLabel()+(StringUtils.isEmpty(collectDto.getProportion())?(proportion+"%"):collectDto.getProportion()):goods_mark.getDictLabel());
                            goodsMarkList.add(mark);
                        }
                    }
                }
            }
        }
        return goodsMarkList;
    }

    @Override
    public List<Goods> selectLittleGoodsListForOne(Goods goods) {
        return goodsMapper.selectLittleGoodsListForOne(goods);
    }

    @Override
    public Integer getGoodsLimitNum(Long goodsId){
        return goodsMapper.getGoodsLimitNum(goodsId);
    }

    /**
     * 为推荐商品排序
     * @param classify
     * @return
     */
    @Override
    public List<GoodsDto> recommendGoodsOrder(List<GoodsDto> goodsDtoList,Long classify) {
        Long recommend = 1L;
        if (classify != recommend){
            log.error("不是推荐分类,不用排序");
            throw new CustomException("不是推荐分类");
        }
        //商品顺序 1有序 0 无序
        String order = GoodsOrderEnum.ORDERLY.getType();

        try {
            //获取商品顺序参数
            JSONObject jsonObject = JSONObject.parseObject((String) sysConfigService.selectConfigByKey("sys.recommendGoods.order"));
            order = jsonObject.getString("order");
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
        if (GoodsOrderEnum.PRICEORDER.getType().equals(order)){
            return goodsDtoList;
        }
        if (GoodsOrderEnum.NOORDER.getType().equals(order)){
            throw new CustomException("商品无序展示");
        }

        //置顶商品
        List<GoodsDto> topGoodsList = Lists.newArrayList();
        Iterator<GoodsDto> iterator = goodsDtoList.iterator();
        while (iterator.hasNext()) {
            GoodsDto goodsDto = iterator.next();
            if (TopGoodsEnum.YES.getType().equals(goodsDto.getTop())) {
                topGoodsList.add(goodsDto);
                iterator.remove();
            }
        }
        Collections.sort(topGoodsList, (a, b) -> {
            int sortA = a.getSort();
            int sortB = b.getSort();
            return sortB - sortA;
        });
        if (GoodsOrderEnum.DISORDER.getType().equals(order)) {
            Collections.shuffle(goodsDtoList);
            for (int i = topGoodsList.size() - 1; i >= 0; i--) {
                goodsDtoList.add(0,topGoodsList.get(i));
            }
        }

        if (GoodsOrderEnum.ORDERLY.getType().equals(order)){
            for (int i = topGoodsList.size() - 1; i >= 0; i--) {
                goodsDtoList.add(0,topGoodsList.get(i));
            }
        }

        return goodsDtoList;
    }

    @Override
    public void shareInformation(ShareDto shareDto, List<GoodsDto> goodsDtoList) {
        if (ApiUtils.getIsLogin()){
            Long courierId = sysUserService.selectUserIdByPhoneNumberAndUserType(ApiUtils.getApiUser().getUser().getPhonenumber(), UserTypeEnum.COURIER.getCode());
            DistributionPoint distributionPoint = distributionPointService.selectPointByCourierId(courierId);
            if (distributionPoint != null){
                for (GoodsDto goodsDto : goodsDtoList) {
                    goodsDto.setTitle(shareDto == null ?("【¥" + goodsDto.getGroupPrice() + "】" + goodsDto.getGoodsName())
                            :(shareDto.getHeadShare().replace("$",distributionPoint.getPointName())+"【¥" + goodsDto.getGroupPrice() + "】" + shareDto.getTitle() + goodsDto.getGoodsName()));
                    goodsDto.setSubtitle(shareDto == null?("【¥" + goodsDto.getGroupPrice() + "】"  + goodsDto.getGoodsName())
                            :(shareDto.getHeadShare().replace("$",distributionPoint.getPointName())+"【¥" + goodsDto.getGroupPrice() + "】" + shareDto.getSubtitle()));
                }
            }else {
                for (GoodsDto goodsDto : goodsDtoList) {
                    goodsDto.setTitle(shareDto == null ?("【¥" + goodsDto.getGroupPrice() + "】" + goodsDto.getGoodsName()):("【¥" + goodsDto.getGroupPrice() + "】" + shareDto.getTitle() + goodsDto.getGoodsName()));
                    goodsDto.setSubtitle(shareDto == null?("【¥" + goodsDto.getGroupPrice() + "】"  + goodsDto.getGoodsName()):("【¥" + goodsDto.getGroupPrice() + "】" + shareDto.getSubtitle()));
                }
            }
        }else {
            for (GoodsDto goodsDto : goodsDtoList) {
                goodsDto.setTitle(shareDto == null ?("【¥" + goodsDto.getGroupPrice() + "】" + goodsDto.getGoodsName()):("【¥" + goodsDto.getGroupPrice() + "】" + shareDto.getTitle() + goodsDto.getGoodsName()));
                goodsDto.setSubtitle(shareDto == null?("【¥" + goodsDto.getGroupPrice() + "】"  + goodsDto.getGoodsName()):("【¥" + goodsDto.getGroupPrice() + "】" + shareDto.getSubtitle()));
            }
        }

    }


    /**
     * 查询捶一捶商品列表
     * @param goods
     * @return
     */
    @Override
    public List<Goods> selectBeatGoodsList(Goods goods) {
        return goodsMapper.selectBeatGoodsList(goods);
    }

    @Override
    public List<GoodsKeyWordsVO> selectKeyWord(String inputWord) {
        if (StringUtils.isEmpty(inputWord)){
            return  null;
        }
        GoodsKeyWordDTO  dto =new GoodsKeyWordDTO();
        dto.setInputWord(inputWord);
        dto.setHandleInputWord(handleString(inputWord));
        return goodsMapper.selectKeyWord(dto);
    }
    private  String  handleString(String result){
        String  subStr=result.substring(0,1);
        result=result.replaceFirst(subStr,subStr+"*");
        return  result;
    }


    public boolean updateGoodsPercentage(Goods goods){
        if(null==goods){
            throw new CustomException("goods is null");
        }
        BigDecimal goodsPrice=null;
        if(goods.getGroupPrice()!=null){
            goodsPrice=new BigDecimal(goods.getGroupPrice());
        }
        BigDecimal percent=null;
        if(StringUtils.isNotEmpty(goods.getPercent())){
            percent= Convert.percentToBigDecimal(goods.getPercent(),null);
        }
        BigDecimal percentage=this.getGoodsPercentage(goods.getBuyPrice(),goodsPrice,percent,goods.getGoodsId());
        try{
            goodsMapper.updateGoodsPercentage(goods.getGoodsId(),percentage);
            return true;
        }catch (Exception e){
            return false;
        }
    }


    @Override
    public BigDecimal getGoodsPercentage(BigDecimal buyPrice,BigDecimal goodsPrice,BigDecimal percent,Long goodsId){
        BigDecimal profit=null;
        if(buyPrice!=null){
            //根据进价计算利润
            profit=this.getProfitByBuyPrice(buyPrice,goodsPrice);
        }
        if(profit!=null&&percent!=null){
            return this.getPercentage(profit,percent);
        }
        return getGoodsPercentageByGoodsPercent(profit,goodsPrice,percent,goodsId);
    }

    public BigDecimal getGoodsPercentageByGoodsPercent(BigDecimal profit,BigDecimal goodsPrice,BigDecimal percent,Long goodsId){
        GoodsPercent goodsPercent=goodsPercentService.selectGoodsPercentByGoodsId(goodsId);
        if(null==profit){
            BigDecimal profitRate=goodsPercent!=null?goodsPercent.getProfitRate():ZERO;
            profit=this.getProfitByProfitRate(goodsPrice,profitRate);
        }
        if(null==percent){
            percent=goodsPercent!=null?goodsPercent.getPercent():ZERO;
        }
        return this.getPercentage(profit,percent);
    }


    /**
     * 根据进价计算商品利润
     * @param buyPrice
     * @param goodsPrice
     * @return
     */
    public BigDecimal getProfitByBuyPrice(BigDecimal buyPrice,BigDecimal goodsPrice){
        if(null==buyPrice){
            throw new CustomException("buyPrice is null");
        }
        if(null==goodsPrice){
            throw new CustomException("goodsPrice is null");
        }
        if(buyPrice.compareTo(goodsPrice)>=0){
            return ZERO;
        }
        return goodsPrice.subtract(buyPrice);
    }

    /**
     * 根据利润率计算商品利润
     * @param goodsPrice
     * @param profitRate
     * @return
     */
    public BigDecimal getProfitByProfitRate(BigDecimal goodsPrice,BigDecimal profitRate){
        if(null==goodsPrice){
            throw new CustomException("goodsPrice is null");
        }
        if(goodsPrice.compareTo(ZERO)==0){
            return ZERO;
        }
        if(null==profitRate){
            throw new CustomException("profitRate is null");
        }
        if(profitRate.compareTo(ZERO)==0){
            return ZERO;
        }
        return goodsPrice.multiply(profitRate);
    }

    @Override
    public boolean relieve(Long goodsId) {
        checkGoodsId(goodsId);
        return goodsMapper.relieve(goodsId)>0;
    }

    @Override
    public boolean establish(Long goodsId, Long wholeGoodsId) {
        checkGoodsId(goodsId);
        checkGoodsId(wholeGoodsId);
        return goodsMapper.establish(goodsId,wholeGoodsId)>0;
    }

    @Override
    public List<Goods> selectGoodsListDtoForOneByGoodsIds() {
        String goodsIds=(String) sysConfigService.selectConfigByKey("sys.vip");
        String[] ids=goodsIds.split(",");
        return goodsMapper.selectGoodsListDtoForOneByGoodsIds(ids);
    }


    private  boolean  checkGoodsId(Long goodsId){
        if (null ==goodsId){
            throw  new CustomException("goodsId是空");
        }
        Goods goods=goodsMapper.selectGoodsById(goodsId);
        if (null==goods){
            throw  new CustomException("没有找到此商品信息");
        }
        return  true;
    }

    /**
     * 计算团长提成
     * @param profit
     * @param percent
     * @return
     */
    public BigDecimal getPercentage(BigDecimal profit,BigDecimal percent){

        if(null==profit){
            throw new CustomException("profit is null");
        }
        if(profit.compareTo(ZERO)==0){
            return ZERO;
        }
        if(null==percent){
            throw new CustomException("percent is null");
        }
        if(percent.compareTo(ZERO)==0){
            return ZERO;
        }
        return profit.multiply(percent);
    }
}
